package com.teddy.DTXMB.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.teddy.DTXMB.Model.Custom;
import com.teddy.DTXMB.Model.ShoppingCart;
import com.teddy.DTXMB.Service.ShoppingCartService;

@Controller
@SessionAttributes("custom")
public class ShoppingCartController {
	/*Log实例*/
	private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	/*购物车详情*/
	@RequestMapping(value = "/shoppingcart", method = RequestMethod.GET)
	public String getShoppingCartByCustomID(HttpServletRequest request, Model model){
		if(request.getSession().getAttribute("custom") != null){
			Custom custom = (Custom)request.getSession().getAttribute("custom");
			int customID = custom.getId();
			/*根据用户ID查出购物车List*/
			List<ShoppingCart> shoppingCart = shoppingCartService.getShoppingCartByCustomID(customID);
			logger.info("ShoppingCart Size: " + Integer.toString(shoppingCart.size()));
			model.addAttribute("shoppingcart", shoppingCart);
			return "shoppingcart";
		}
		else
		{
			return "errorcustom";
		}
	}
	
	/*@ResponseBody注解用于将Controller的方法返回的对象，通过适当的HttpMessageConverter转换为指定格式后，写入到Response对象的body数据区。*/
	/*使用时机：返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用*/
	@RequestMapping(value = "/shoppingcart/add", method = RequestMethod.POST, produces="application/json")
	@ResponseBody
	public Map<String, Object> addShoppingCart(HttpServletRequest request, @RequestBody int productID){
		if(request.getSession().getAttribute("custom") != null){
			Custom custom = (Custom)request.getSession().getAttribute("custom");
			ShoppingCart sCart = new ShoppingCart();
			sCart.setCustomid(custom.getId());
			sCart.setProductid(productID);
			sCart.setProductnumber(1);
			
			if (shoppingCartService.addToShoppingCart(sCart)){
				Map<String, Object> modelMap = new HashMap<String, Object>(1);
				int cartNumber = shoppingCartService.getShoppingCartByCustomID(custom.getId()).size();
				modelMap.put("returnInt", cartNumber);
				return modelMap;
			}
			else{
				return null;
			}
		}
		else{
			return null;
		}
	}
}